package com.cp.util;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Des:
 * 日志记录构建
 *
 * @author XL
 * @Date 2022/7/15 10:40
 */
@Slf4j
public class LogBuilder {
    private Logger logger;

    private String remark;

    private final Map<Object, Object> BODY = new HashMap<>();

    private String expression;

    private Level level;

    private Exception e;

    public static LogBuilder builder() {
        return new LogBuilder();
    }

    public LogBuilder init(Logger logger, Level level) {
        this.logger = logger;
        this.level = level;
        return this;
    }


    public LogBuilder remark(String remark) {
        this.remark = remark;
        return this;
    }

    public LogBuilder body(Object key, Object val) {
        BODY.put(key, val);
        return this;
    }

    public LogBuilder e(Exception e) {
        this.e = e;
        return this;
    }

    private void check() {
        if (this.logger == null || this.remark == null || this.level == null) {
            throw new IllegalArgumentException("非法参数异常");
        }
    }

    public void build() {
        //参数校验
        check();
        StringBuilder builder = new StringBuilder();
        if (!StringUtils.isEmpty(remark)) {
            builder
                    .append("[")
                    .append(remark)
                    .append("]")
                    .append(":");
        }
        BODY.forEach((k, v) -> {
            builder.append(k)
                    .append("=")
                    .append(v)
                    .append(",");
        });
        expression = builder.toString();
        expression = expression.substring(0, expression.length() - 1);
        recordLog();
    }

    private void recordLog() {
        if (Level.DEBUG.getLevel().equals(level.level)) {
            this.logger.debug(expression, e);
        } else if (Level.INFO.getLevel().equals(level.level)) {
            this.logger.info(expression, e);
        } else if (Level.WARN.getLevel().equals(level.level)) {
            this.logger.warn(expression, e);
        } else if (Level.ERROR.getLevel().equals(level.level)) {
            this.logger.error(expression, e);
        }
    }

    @Getter
    @AllArgsConstructor
    public enum Level {
        /**
         * 调试
         */
        DEBUG("DEBUG", "调试"),
        /**
         * 默认日常信息
         */
        INFO("INFO", "默认日常信息"),
        /**
         * 告警
         */
        WARN("WARN", "告警"),
        /**
         * 错误
         */
        ERROR("ERROR", "错误");
        private final String level;
        private final String desc;
    }
}


